# -*- coding: utf-8 -*-
import sys
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                            QHBoxLayout, QLabel, QLineEdit, QPushButton,
                            QTableWidget, QTableWidgetItem, QHeaderView,
                            QMessageBox, QStackedWidget, QComboBox, QFormLayout,
                            QStyleFactory)  # 添加缺失的导入
from PyQt5.QtGui import QFont,QIcon
from tqsdk import TqApi, TqAuth, TqAccount, TqSim

class CapitalManager(QMainWindow):
    update_signal = pyqtSignal(str)
    connection_signal = pyqtSignal(str, bool)

    def _connect_thread(self):
        try:
            # 修正经纪商代码为官方格式（关键修复）
            self.tq_account = TqAccount("H徽商期货", "155831", "alibaba999")  
            self.api = TqApi(account=self.tq_account,
                           auth=TqAuth("szlwy68", "alibaba999"),
                           _stock=False)
            self.macc=self.api.get_account()
            print("已经成功连接天勤账户")
            print("当前账户可用资金：",self.macc.available)
            
            # 修正f-string语法错误
            self.update_signal.emit(f"{self.macc.available:.2f}")  # 新增
            
            # 发射连接成功信号
            self.connection_signal.emit("已连接 (点击断开)", True)
            self.update_capital()  # 启动资金更新线程
            
        except Exception as e:
            self.connection_signal.emit(f"连接失败: {str(e)}", False)

    def handle_connection(self, text, success):
        """处理连接状态更新"""
        self.connect_btn.setText(text)
        self.connect_btn.setEnabled(True)
        if success:
            # 断开原有连接并绑定断开方法
            try:
                self.connect_btn.clicked.disconnect()
            except TypeError:
                pass
            self.connect_btn.clicked.connect(lambda: self.disconnect_tq())
            QApplication.processEvents()
            # 删除下面这行已移除的方法调用
            # self.update_capital()  # <<< 这行需要删除
        else:
            # 重新绑定连接方法（关键修复）
            try:
                self.connect_btn.clicked.disconnect()
            except TypeError:
                pass
            self.connect_btn.clicked.connect(self.connect_tq)

    def connect_tq(self):
        """天勤账户连接主方法"""
        try:
            self.connect_btn.setEnabled(False)
            self.connect_btn.setText("连接中...")
            
            from threading import Thread
            Thread(target=self._connect_thread, daemon=True).start()
            
        except Exception as e:
            self.connect_btn.setEnabled(True)
            QMessageBox.critical(self, "错误", f"启动连接失败: {str(e)}")

    def disconnect_tq(self):  # 新增断开连接方法
        """断开天勤账户连接"""
        try:
            if self.api:
                self.api.close()
                self.api = None
                self.tq_account = None
                self.connect_btn.setText("连接天勤账户")
                self.capital_input.clear()
                QMessageBox.information(self, "断开成功", "已断开天勤账户连接")
                
                # 重新绑定连接方法
                self.connect_btn.clicked.disconnect()
                self.connect_btn.clicked.connect(self.connect_tq)
                
        except Exception as e:
            QMessageBox.critical(self, "断开错误", f"断开连接时发生错误: {str(e)}")

    def closeEvent(self, event): 
        self.disconnect_tq()
        event.accept()

    def _connect_thread(self):
        try:
            self.tq_account = TqAccount("H徽商期货", "155831", "alibaba999")  
            self.api = TqApi(account=self.tq_account,
                           auth=TqAuth("szlwy68", "alibaba999"),
                           _stock=False)
            
            self.macc=self.api.get_account()
            print("已经成功连接天勤账户")
            print("当前账户可用资金：",self.macc.available)
            
            self.update_signal.emit(f"{self.macc.available:.2f}") 
            self.connection_signal.emit("已连接 (点击断开)", True)
            
        except Exception as e:
            self.connection_signal.emit(f"连接失败: {str(e)}", False)

    def __init__(self):
        super().__init__()
        self.init_data()  # 初始化数据必须在最前面
        self.init_ui()
        self.setup_connections()
        self.setWindowTitle("资金管理系统")
        self.resize(1200, 800)
        self.handle_page_change(0)

    # 添加 init_data 方法定义（必须位于类内部）
    def init_data(self):
        """初始化业务数据"""
        self.products = [
            {'name': '螺纹钢2501', 'exchange_code': 'SHFE.rb2501', 'margin': 5000, 'stoploss': 50, 'multiplier': 10},
            {'name': '棕榈油2509', 'exchange_code': 'DCE.p2509', 'margin': 6000, 'stoploss': 80, 'multiplier': 10},
            {'name': '沪铜2409', 'exchange_code': 'SHFE.cu2409', 'margin': 35000, 'stoploss': 200, 'multiplier': 5},
            {'name': '沪深300', 'exchange_code': 'CFFEX.IF2409', 'margin': 120000, 'stoploss': 30, 'multiplier': 300},
            {'name': '黄金2410', 'exchange_code': 'SHFE.au2410', 'margin': 40000, 'stoploss': 2, 'multiplier': 1000},
            {'name': '原油2409', 'exchange_code': 'INE.sc2409', 'margin': 80000, 'stoploss': 10, 'multiplier': 100},
            {'name': '豆粕2501', 'exchange_code': 'DCE.m2501', 'margin': 4500, 'stoploss': 40, 'multiplier': 10},
            {'name': 'PTA2501', 'exchange_code': 'CZCE.TA2501', 'margin': 3500, 'stoploss': 60, 'multiplier': 5},
            {'name': '玻璃2501', 'exchange_code': 'CZCE.FG2501', 'margin': 3000, 'stoploss': 30, 'multiplier': 20},
            {'name': '白糖2501', 'exchange_code': 'CZCE.SR2501', 'margin': 4000, 'stoploss': 40, 'multiplier': 10}
        ]
        self.api = None
        self.tq_account = None

    def init_ui(self):
        # ==== 主布局修复 ====
        main_widget = QWidget()
        main_h_layout = QHBoxLayout(main_widget)
        
        # ==== 左侧面板 ====
        side_panel = QWidget()
        side_layout = QVBoxLayout(side_panel)  # 只保留一次布局初始化
        
        # +++ 更新后的按钮配置 +++
        self.btn_calculate = QPushButton("计算下单量")
        self.btn_order = QPushButton("下单")
        self.btn_set_sl = QPushButton("设置止盈止损")
        self.btn_auto_sl = QPushButton("启动自动止盈止损")
        self.btn_sl_params = QPushButton("设置止盈止损参数")
        
        # 设置按钮属性
        button_group = [
            self.btn_calculate, 
            self.btn_order,
            self.btn_set_sl,
            self.btn_auto_sl,
            self.btn_sl_params
        ]
        for btn in button_group:
            btn.setCheckable(True)
            btn.setMinimumHeight(40)
            btn.setMinimumWidth(200)
            side_layout.addWidget(btn)  # 直接在此处添加按钮
            
        side_layout.addStretch()
        
        # ==== 右侧堆叠窗口 ====
        self.stacked_widget = QStackedWidget()
        self._init_capital_ui()  # 页面0
        self.init_order_ui()     # 页面1
        
        # 新增三个空白页面（需要创建实际内容）
        self.stacked_widget.addWidget(QWidget())  # 页面2（设置止盈止损）
        self.stacked_widget.addWidget(QWidget())  # 页面3（自动止盈止损）
        self.stacked_widget.addWidget(QWidget())  # 页面4（止盈止损参数）
        
        # 组合布局
        main_h_layout.addWidget(side_panel)
        main_h_layout.addWidget(self.stacked_widget, stretch=1)
        self.setCentralWidget(main_widget)

    def setup_connections(self):
        """连接信号与槽函数"""
        # 连接所有侧边栏按钮
        self.btn_calculate.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(0))  # 页面0
        self.btn_order.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(1))      # 页面1
        self.btn_set_sl.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(2))     # 页面2
        self.btn_auto_sl.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(3))    # 页面3
        self.btn_sl_params.clicked.connect(lambda: self.stacked_widget.setCurrentIndex(4)) # 页面4
        
        # 连接账户按钮
        self.connect_btn.clicked.connect(self.connect_tq)
        
        # 连接更新信号
        self.update_signal.connect(lambda x: self.capital_input.setText(x))
        self.connection_signal.connect(self.handle_connection)
        
        # 页面切换处理
        self.stacked_widget.currentChanged.connect(self.handle_page_change)


    def handle_page_change(self, index):
        """处理页面切换时的按钮样式"""
        # 所有侧边栏按钮列表
        buttons = [
            self.btn_calculate,    # 0
            self.btn_order,        # 1
            self.btn_set_sl,       # 2
            self.btn_auto_sl,      # 3
            self.btn_sl_params     # 4
        ]
        
        # 更新所有按钮状态和样式
        for i, btn in enumerate(buttons):
            is_active = (i == index)
            btn.setChecked(is_active)
            
            btn.setStyleSheet(f"""
                QPushButton {{
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 {'#f0f8ff' if is_active else '#f5f5f5'}, 
                        stop:1 {'#c6e2ff' if is_active else '#e0e0e0'});
                    color: {'#2196F3' if is_active else '#666'};
                    font-weight: {'bold' if is_active else 'normal'};
                    border: 1px solid {'#90caf9' if is_active else '#bdbdbd'};
                    border-radius: 4px;
                    padding: 10px;
                    margin: 2px;
                    border-bottom: 2px solid {'rgba(33,150,243,0.3)' if is_active else 'rgba(0,0,0,0.1)'};
                }}
                QPushButton:hover {{
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 {'#e3f2fd' if is_active else '#eee'}, 
                        stop:1 {'#b3d4fc' if is_active else '#d5d5d5'});
                }}
                QPushButton:pressed {{
                    background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                        stop:0 {'#bbdefb' if is_active else '#e0e0e0'}, 
                        stop:1 {'#90caf9' if is_active else '#bdbdbd'});
                    border-top: 2px solid rgba(0,0,0,0.1);
                    border-bottom: 0px;
                }}
            """)




    def _init_capital_ui(self):
        """资金管理界面初始化"""
        capital_widget = QWidget()
        layout = QVBoxLayout(capital_widget)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 恢复资金管理界面原有的UI组件
        self.connect_btn = QPushButton("连接天勤账户")
        self.connect_btn.clicked.connect(self.connect_tq)
        layout.addWidget(self.connect_btn)
        
        # 输入区域
        input_layout = QHBoxLayout()
        self.capital_input = QLineEdit()
        self.capital_input.setPlaceholderText("正在获取账户资金...")
        self.capital_input.setReadOnly(True)
        input_layout.addWidget(QLabel("账户可用资金:"))
        input_layout.addWidget(self.capital_input)
        
        self.risk_input = QLineEdit()
        self.risk_input.setPlaceholderText("输入风险比例（%）")
        self.risk_input.setText("20")
        input_layout.addWidget(QLabel("风险比例:"))
        input_layout.addWidget(self.risk_input)
        layout.addLayout(input_layout)
        
        # 计算按钮
        self.calc_btn = QPushButton("计算下单量")
        self.calc_btn.clicked.connect(self.calculate)
        layout.addWidget(self.calc_btn)
        
        # 表格
        self.table = QTableWidget()
        self.table.setColumnCount(5)
        self.table.setHorizontalHeaderLabels(["品种", "保证金", "止损金额", "建议开仓量", "最大开仓量"])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.table)

        # +++ 新增公式说明 +++
        formula_label = QLabel("""
            <div style='margin:15px 0; color:#666; font-size:12px;'>
                <b>计算公式说明：</b>
                <ul>
                    <li>风险资金 = 账户资金 × 风险比例</li>
                    <li>建议开仓量 = 风险资金 ÷ (保证金 × 3)</li>
                    <li>最大开仓量 = 风险资金 ÷ 保证金</li>
                    <li>止损金额 = 止损点数 × 合约乘数 × 价格单位</li>
                </ul>
                <div style='color:#2196F3;'>注：建议开仓量采用1/3仓位原则，最大开仓量表示当前风险承受下的极限仓位</div>
            </div>
        """)
        formula_label.setWordWrap(True)
        layout.addWidget(formula_label)

        self.stacked_widget.addWidget(capital_widget)


    def calculate(self):  
        """执行资金计算逻辑"""
        try:
            # 获取输入值
            risk_percent = float(self.risk_input.text())
            capital = float(self.capital_input.text()) if self.capital_input.text() else 0
            
            if risk_percent <= 0 or risk_percent > 100:
                raise ValueError("风险比例需在 0-100% 之间")
                
            # 清空表格
            self.table.setRowCount(0)
            
            # 计算每个品种的开仓量
            for product in self.products:
                max_lots = (capital * risk_percent / 100) / product['margin']
                suggested_lots = int(max_lots // 3)
                
                # 添加表格行
                row = self.table.rowCount()
                self.table.insertRow(row)
                
                # 填充数据
                self.table.setItem(row, 0, QTableWidgetItem(product['name']))
                self.table.setItem(row, 1, QTableWidgetItem(str(product['margin'])))
                self.table.setItem(row, 2, QTableWidgetItem(str(product['stoploss'])))
                self.table.setItem(row, 3, QTableWidgetItem(str(suggested_lots)))
                self.table.setItem(row, 4, QTableWidgetItem(f"{max_lots:.1f}"))
                
        except ValueError as e:
            QMessageBox.warning(self, "输入错误", str(e))
        except Exception as e:
            QMessageBox.critical(self, "计算错误", f"发生未知错误: {str(e)}")


    def init_order_ui(self):  # 恢复订单页面初始化
        """订单页面初始化"""
        order_widget = QWidget()
        layout = QVBoxLayout(order_widget)
        layout.setContentsMargins(15, 15, 15, 15)
        
        # 添加订单界面基础组件
        self.symbol_combo = QComboBox()
        self.symbol_combo.addItems([p['name'] for p in self.products])
        
        self.quantity_input = QLineEdit()
        self.quantity_input.setPlaceholderText("输入下单数量")
        
        order_btn = QPushButton("提交订单")
        order_btn.clicked.connect(self.submit_order)
        
        form_layout = QFormLayout()
        form_layout.addRow("选择品种:", self.symbol_combo)
        form_layout.addRow("下单数量:", self.quantity_input)
        
        layout.addLayout(form_layout)
        layout.addWidget(order_btn)
        layout.addStretch()
        
        self.stacked_widget.insertWidget(1, order_widget)  # 插入到页面1的位置


    def submit_order(self):  # 新增订单提交方法
        """处理订单提交"""
        try:
            # 获取选择的品种
            selected_product = self.products[self.symbol_combo.currentIndex()]
            quantity = int(self.quantity_input.text())
            
            if quantity <= 0:
                raise ValueError("下单数量必须大于0")
                
            # 获取合约代码
            symbol = selected_product['exchange_code']
            
            # 实际下单逻辑（需要连接账户）
            if not self.api:
                raise RuntimeError("请先连接天勤账户")
            
            # 创建订单
            order = self.api.insert_order(
                symbol=symbol,
                direction="BUY",  # 默认先做多
                offset="OPEN",
                volume=quantity
            )
            
            QMessageBox.information(self, "下单成功", f"已提交{symbol} {quantity}手买单")
            
        except ValueError as e:
            QMessageBox.warning(self, "输入错误", str(e))
        except Exception as e:
            QMessageBox.critical(self, "下单失败", f"错误信息: {str(e)}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    # 修正后的样式设置（确保QStyleFactory已导入）
    app.setStyle(QStyleFactory.create("WindowsVista")) 
    app.setFont(QFont("微软雅黑", 9))
    app.setStyleSheet("""
        * {
            font-family: "微软雅黑", "Consolas";
        }
        QLineEdit, QTableWidget, QLabel {
            font: 10pt "Consolas", "微软雅黑";
        }
        QTableWidget {
            background-color: white;
            border: 1px solid #E0E0E0;
            margin-top: 10px;
        }
        QTableWidget::item {
            padding: 5px;
        }
        QLineEdit {
            min-height: 25px;
            padding: 2px 5px;
        }
        QTableWidget {
            min-width: 800px;  /* 新增最小宽度 */
        }
        QLineEdit {
            min-width: 150px;
        }
        QComboBox {
            min-width: 200px;
        }
    """)
    app.setWindowIcon(QIcon('app.png'))
    window = CapitalManager()
    window.show()
    sys.exit(app.exec_())